<template>
  <div class="container">
    <Breadcrumb
      :items="['menu.systemManger', 'menu.systemManger.userManger']"
    />
    <a-card class="general-card" :title="$t('menu.systemManger.userManger')">
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleClick('add')">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('userManger.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('userManger.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('userManger.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('userManger.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="handleChange($event, item, index)"
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #contentType="{ record }">
          <a-space>
            <a-avatar
              v-if="record.contentType === 'img'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/581b17753093199839f2e327e726b157.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar
              v-else-if="record.contentType === 'horizontalVideo'"
              :size="16"
              shape="square"
            >
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/77721e365eb2ab786c889682cbc721c1.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            <a-avatar v-else :size="16" shape="square">
              <img
                alt="avatar"
                src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/ea8b09190046da0ea7e070d83c5d1731.svg~tplv-49unhts6dw-image.image"
              />
            </a-avatar>
            {{ $t(`userManger.form.contentType.${record.contentType}`) }}
          </a-space>
        </template>
        <template #filterType="{ record }">
          {{ $t(`userManger.form.filterType.${record.filterType}`) }}
        </template>
        <template #status="{ record }">
          <span v-if="record.status === 'offline'" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ $t(`userManger.form.status.${record.status}`) }}
        </template>
        <template #operations="scope">
          <a-button
            type="text"
            size="small"
            @click="handleClick('view', scope.record)"
          >
            {{ $t('userManger.columns.operations.view') }}
          </a-button>
          <a-button
            type="text"
            size="small"
            @click="handleClick('edit', scope.record)"
          >
            {{ $t('userManger.columns.operations.edit') }}
          </a-button>
          <a-popconfirm
            :content="$t('userManger.operations.remove.content')"
            type="error"
            @before-ok="(done) => handleRemove(done, scope.record.id)"
          >
            <a-button type="text" size="small">
              {{ $t('userManger.columns.operations.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="formVisible"
      :title="$t(`userManger.form.title.${formFlag}`)"
      :mask-closable="false"
      @cancel="handleCancel"
      @before-ok="handleBeforeOk"
    >
      <a-form ref="formRef" :model="form" :disabled="'view'.includes(formFlag)">
        <a-form-item
          field="username"
          required
          :label="$t(`userManger.form.username`)"
        >
          <a-input
            v-model="form.username"
            :rules="[
              {
                required: true,
                message: $t('userManger.form.username.errMsg'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
          />
        </a-form-item>
        <a-form-item
          field="email"
          required
          :label="$t(`userManger.form.email`)"
        >
          <a-input
            v-model="form.email"
            :rules="[
              {
                required: true,
                message: $t('userManger.form.email.errMsg'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
          />
        </a-form-item>

        <a-form-item
          v-if="!'view'.includes(formFlag)"
          field="password"
          :required="'add'.includes(formFlag)"
          :label="$t(`userManger.form.password`)"
        >
          <a-input-password
            v-model="form.password"
            autocomplete="off"
            :rules="[
              {
                required: true,
                message: $t('userManger.form.password.errMsg'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {
    addUser,
    delUser,
    editUser,
    queryPage,
  } from '@/api/systemManger/userManger';
  import {
    UserForm,
    UserListParams,
    UserRecord,
  } from '@/api/systemManger/userManger/types';

  import { Pagination } from '@/types/global';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { Message, ValidatedError } from '@arco-design/web-vue';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      username: undefined,
      email: undefined,
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<UserRecord[]>([]);
  const formModel = ref(generateFormModel());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const densityList = computed(() => [
    {
      name: t('userManger.size.mini'),
      value: 'mini',
    },
    {
      name: t('userManger.size.small'),
      value: 'small',
    },
    {
      name: t('userManger.size.medium'),
      value: 'medium',
    },
    {
      name: t('userManger.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('userManger.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
    },
    {
      title: t('userManger.columns.username'),
      dataIndex: 'username',
    },
    {
      title: t('userManger.columns.email'),
      dataIndex: 'email',
    },
    {
      title: t('userManger.columns.createTime'),
      dataIndex: 'createTime',
    },
    {
      title: t('userManger.columns.updateTime'),
      dataIndex: 'updateTime',
    },
    {
      title: t('userManger.columns.operations'),
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ]);

  const fetchData = async (
    params: UserListParams = { current: 1, pageSize: 20 }
  ) => {
    setLoading(true);
    try {
      const { data } = await queryPage(params);
      renderData.value = data.records;
      pagination.current = data.current;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as UserListParams);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  const formRef = ref<HTMLFormElement | null>(null);
  const formVisible = ref(false);
  const formFlag = ref('add');
  const form = ref<UserForm>({});

  const handleBeforeOk = (done: (closed: boolean) => void) => {
    const submitApi = 'add'.includes(formFlag.value) ? addUser : editUser;
    formRef.value?.validate(
      async (err: undefined | Record<string, ValidatedError>) => {
        if (!err) {
          try {
            await submitApi(form.value);
            Message.success(t(`userManger.form.${formFlag.value}.success`));
            form.value = {};
            search();
            return done(true);
          } catch (e) {
            Message.error(t(`userManger.form.${formFlag.value}.error`));
            return done(false);
          }
        }
        return done(false);
      }
    );
  };
  const handleCancel = () => {
    formVisible.value = false;
    form.value = {};
  };
  const handleClick = (flag: string, record: UserForm = {}) => {
    form.value = { ...record };
    formFlag.value = flag;
    formVisible.value = true;
  };
  const handleRemove = async (done: (closed: boolean) => void, id: number) => {
    try {
      await delUser(id);
      Message.success(t(`userManger.form.remove.success`));
      search();
      return done(true);
    } catch (e) {
      Message.error(t(`userManger.form.remove.error`));
      return done(false);
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, _) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'UserManger',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
